package server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import protocol.Packet;
import protocol.PacketCodeC;
import protocol.request.LoginRequestPacket;
import protocol.request.MessageRequest;
import protocol.response.LoginResponsePacket;
import protocol.response.MessageResponse;

import java.util.Date;

public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf message = (ByteBuf) msg;

        Packet packet = PacketCodeC.INSTANCE.decode(message);

        if (packet instanceof LoginRequestPacket) {
            LoginRequestPacket requestPacket = (LoginRequestPacket) packet;
            LoginResponsePacket loginResponsePacket = new LoginResponsePacket();

            if (!valid(requestPacket)){
                loginResponsePacket.setSuccess(false);
                loginResponsePacket.setReason("用户名或密码错误");
                System.out.println(new Date() + ":登录失败");
            }else {
                loginResponsePacket.setSuccess(true);
                System.out.println(new Date() + ":登录成功");
            }
            ByteBuf encode = PacketCodeC.INSTANCE.encode(ctx.alloc(), loginResponsePacket);
            ctx.channel().writeAndFlush(encode);
        } else if (packet instanceof MessageRequest) {
            MessageRequest messageRequest = (MessageRequest) packet;
            System.out.println(new Date() + ":服务端接收到客户端消息:" + messageRequest.getMessage());

            MessageResponse messageResponse = new MessageResponse();
            messageResponse.setMessage("服务端回复【" + messageRequest.getMessage() + "】");

            ByteBuf encode = PacketCodeC.INSTANCE.encode(ctx.alloc(), messageResponse);
            ctx.channel().writeAndFlush(encode);
        }

    }


    private boolean valid(LoginRequestPacket loginRequestPacket) {
        return true;
    }
}
